<script setup lang="ts">
import { pwEditApi } from '@/api/System/user';
import { notify } from '@/utils/anted';
import { Modal, Form, FormItem, Switch, Input, Textarea } from 'ant-design-vue';
import { reactive, toRaw } from 'vue';

// 定义状态
const state = reactive({
  visible: false,
  title: '新增',
  type: 'add'
});

const useForm = Form.useForm;
const modelStateRef = reactive({
  roleName: '',
  roleCode: '',
  status: '',
  remark: ''
});
const rulesRef = reactive({
  roleName: [
    {
      required: true,
      message: '请输入角色名称'
    }
  ],
  roleCode: [
    {
      required: true,
      message: '请输入权限标识'
    }
  ],
  status: [
    {
      required: true,
      message: '请输入选择状态',
      trigger: 'change'
    }
  ]
});
const { validate, validateInfos, resetFields } = useForm(
  modelStateRef,
  rulesRef
);
const onSubmit = () => {
  validate()
    .then(async () => {
      if (state.type === 'add') {
        await pwEditApi('');
        notify('角色新增成功！', { type: 'success' });
      } else {
        await pwEditApi('');
        notify('角色修改成功！', { type: 'success' });
      }
      state.visible = false;
    })
    .catch(err => {
      console.log('error', err);
    });
};
const open = (type: any, title: any, row: any) => {
  state.title = title;
  state.type = type;
  if (row) {
    modelStateRef.roleName = row.roleName;
    modelStateRef.roleCode = row.roleCode;
    modelStateRef.status = row.status;
    modelStateRef.remark = row.remark;
  }
  state.visible = true;
};
// 导出给父组件调用
defineExpose({
  open
});
</script>
<template>
  <Modal
    v-model:open="state.visible"
    :title="state.title"
    @ok="onSubmit"
    destroyOnClose
    @cancel="resetFields"
  >
    <Form :labelCol="{ style: 'width: 100px' }">
      <FormItem label="角色名称" v-bind="validateInfos.roleName">
        <Input
          v-model:value="modelStateRef.roleName"
          placeholder="请输入角色名称"
        />
      </FormItem>
      <FormItem label="权限标识" v-bind="validateInfos.roleCode">
        <Input
          v-model:value="modelStateRef.roleCode"
          placeholder="保证唯一性，建议以`ROLE_`开头"
        />
      </FormItem>
      <FormItem label="状态" v-bind="validateInfos.status">
        <Switch
          checked-children="启"
          un-checked-children="停"
          v-model:checked="modelStateRef.status"
        />
      </FormItem>
      <FormItem label="备注">
        <Textarea
          v-model:value="modelStateRef.remark"
          placeholder="请输入备注"
        />
      </FormItem>
    </Form>
  </Modal>
</template>

<style scoped></style>
